from typing import *


class Solution:
    def surfaceArea(self, grid: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])
        ans = 0
        for i in range(m):
            for j in range(n):
                v = grid[i][j]
                ans += 2 if v > 0 else 0
                ans += v if i == 0 else max(0, v - grid[i - 1][j])
                ans += v if i == m - 1 else max(0, v - grid[i + 1][j])
                ans += v if j == 0 else max(0, v - grid[i][j - 1])
                ans += v if j == n - 1 else max(0, v - grid[i][j + 1])
        return ans
